<template>
    <view class="interview-container">
        <!-- 顶部固定的筛选栏 -->
        <view class="filter-bar">
            <view class="difficulty-tabs">
                <view v-for="option in difficultyOptionsWithAll" :key="option.value"
                    :class="['tab-item', currentDifficulty == option.value ? 'active' : '']"
                    @click="currentDifficulty = option.value">
                    {{ option.label }}
                </view>
            </view>

            <!-- 会员/非会员选择 + 显示答案开关 -->
            <view class="filter-row">
                <view class="premium-tabs">
                    <view :class="['tab-item', requirePremium === '' ? 'active' : '']" @click="requirePremium = ''">
                        全部
                    </view>
                    <view :class="['tab-item', requirePremium === 'false' ? 'active' : '']"
                        @click="requirePremium = 'false'">
                        免费
                    </view>
                    <view :class="['tab-item', requirePremium === 'true' ? 'active' : '']"
                        @click="requirePremium = 'true'">
                        VIP
                    </view>
                </view>

                <view class="show-answers-control">
                    <text class="show-text">显示所有答案</text>
                    <switch :checked="showAllAnswers" @change="toggleAllAnswers" />
                    <text class="total-count">总题数: {{ total }}</text>
                </view>
            </view>
        </view>

        <!-- 内容区域 -->
        <scroll-view class="content-scroll" scroll-y @scrolltolower="loadMore" refresher-enabled
            @refresherrefresh="onRefresh" :refresher-triggered="isRefreshing">
            <view class="content-wrapper">
                <!-- 题目列表 -->
                <view class="interview-list">
                    <!-- 加载状态 -->
                    <view v-if="loading && !loadingMore" class="loading-container">
                        <text>加载中...</text>
                    </view>

                    <!-- 错误状态 -->
                    <view v-else-if="error" class="error-container">
                        <text class="error-text">{{ error }}</text>
                    </view>

                    <!-- 空状态 -->
                    <view v-else-if="interviews.length === 0 && !loading" class="empty-container">
                        <text class="empty-text">没有找到相关前端宝典</text>
                    </view>

                    <!-- 题目卡片 -->
                    <view v-else class="interview-cards">
                        <view v-for="interview in interviews" :key="interview.id" class="interview-card">
                            <!-- VIP角标 -->
                            <view v-if="interview.requirePremium" class="vip-badge">
                                <text class="vip-text">VIP</text>
                            </view>

                            <!-- 题目标题和难度 -->
                            <view class="card-header">
                                <text class="question-title">{{ interview.question }}</text>
                                <view :class="['difficulty-tag', getDifficultyClass(interview.difficulty)]">
                                    {{ getDifficultyText(interview.difficulty) }}
                                </view>
                            </view>

                            <!-- 答案和切换按钮 -->
                            <view class="card-content">
                                <view class="content-header">
                                    <view class="meta-info">
                                        <text class="category">分类：{{ getCategoryName(interview.categoryId) }}</text>
                                        <text class="date">{{ formatDate(interview.createTime) }}</text>
                                    </view>

                                    <view class="toggle-answer-btn" @click="toggleAnswer(interview)">
                                        <text class="btn-text">
                                            {{ answerVisibility[interview.id] ? '隐藏答案' : '查看答案' }}
                                        </text>
                                    </view>
                                </view>

                                <!-- 答案内容 -->
                                <view v-if="answerVisibility[interview.id]" class="answer-content">
                                    <view v-if="interview.answer" class="answer-wrapper">
                                        <view class="answer-header">
                                            <view class="answer-indicator"></view>
                                            <text class="answer-label">回答</text>
                                        </view>
                                        <rich-text :nodes="formatAnswer(interview.answer)"
                                            class="answer-text"></rich-text>
                                    </view>
                                    <view v-else class="answer-loading">
                                        <text>{{ interview.requirePremium && !isPremium ? '此答案需要会员权限才能查看' : '加载中...'
                                        }}</text>
                                    </view>

                                    <!-- 点赞/收藏操作 -->
                                    <view v-if="interview.answer && !interview.answer.includes('该内容为VIP专享')"
                                        class="action-buttons">
                                        <button :class="['action-btn', interview.isLiked ? 'liked' : '']"
                                            @click="handleLike(interview)">
                                            <SvgIcon :name="interview.isLiked ? 'like2' : 'like'" :size="16" />
                                            <text class="btn-count">{{ interview.likeCount }}</text>
                                        </button>

                                        <button :class="['action-btn', interview.isFavorited ? 'favorited' : '']"
                                            @click="handleFavorite(interview)">
                                            <SvgIcon :name="interview.isFavorited ? 'save2' : 'save'" :size="16" />
                                            <text class="btn-count">{{ interview.favoriteCount }}</text>
                                        </button>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>

                    <!-- 加载更多 -->
                    <view v-if="loadingMore" class="load-more">
                        <text>加载更多...</text>
                    </view>

                    <view v-else-if="!hasMore && interviews.length > 0" class="no-more">
                        <text>已经到底啦 ~</text>
                    </view>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { getInterviewList, getInterviewAnswer, favoriteInterview, likeInterview } from '@/api/interview'
import { difficultyOptions, difficultyMap } from '@/api/constants'
import { useUserStore } from '@/stores/user'

// 用户信息
const userStore = useUserStore()
const isPremium = ref(false)

// 前端宝典列表
const interviews = ref<any[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const error = ref<string | null>(null)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const hasMore = ref(true)
const isRefreshing = ref(false)

// 筛选条件
const currentDifficulty = ref<number | string>(0) // 0 表示全部
const requirePremium = ref<string>('') // 空字符串表示全部
const selectedCategory = ref<string | number>('all') // 默认为全部
const showAllAnswers = ref(false) // 控制是否显示所有答案

// 记录每个题目答案的显示状态
const answerVisibility = ref<Record<number, boolean>>({})

// 难度选项（包含全部）
const difficultyOptionsWithAll = computed(() => [
    { value: 0, label: '全部' },
    ...difficultyOptions
])

// 获取前端宝典列表
const fetchInterviews = async (isLoadMore = false) => {
    // 防止重复请求
    if ((isLoadMore && loadingMore.value) || (!isLoadMore && loading.value)) return

    if (isLoadMore) {
        loadingMore.value = true
    } else {
        loading.value = true
    }

    error.value = null

    try {
        // 构建请求参数
        const params: any = {
            page: page.value,
            pageSize: pageSize.value
        }

        // 添加筛选条件
        if (currentDifficulty.value !== 0) {
            params.difficulty = currentDifficulty.value
        }

        if (requirePremium.value !== '') {
            params.requirePremium = requirePremium.value === 'true'
        }

        if (selectedCategory.value !== 'all') {
            params.categoryId = selectedCategory.value
        }

        const { data } = await getInterviewList(params)
        console.log('data', data)
        if (isLoadMore) {
            interviews.value = [...interviews.value, ...data.list]
        } else {
            interviews.value = data.list
        }

        total.value = data.total
        hasMore.value = interviews.value.length < total.value
    } catch (err) {
        console.error('获取前端宝典列表失败:', err)
        error.value = '获取前端宝典列表失败'
        uni.showToast({
            title: '获取前端宝典列表失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
        loadingMore.value = false
        isRefreshing.value = false
    }
}

// 下拉刷新
const onRefresh = () => {
    isRefreshing.value = true
    page.value = 1
    interviews.value = []
    answerVisibility.value = {}
    fetchInterviews()
}

// 加载更多前端宝典
const loadMore = async () => {
    // 如果正在加载或没有更多数据，直接返回
    if (loadingMore.value || !hasMore.value) return

    page.value++
    await fetchInterviews(true)
}

// 获取答案
const getAnswer = async (id: number) => {
    if (!userStore.token) {
        uni.showToast({
            title: '请先登录',
            icon: 'none'
        })
        return
    }

    try {
        const { data } = await getInterviewAnswer(id)
        return data.answer
    } catch (err: any) {
        // 处理会员权限错误
        if (err.response && err.response.status === 403) {
            uni.showToast({
                title: '此答案需要会员权限才能查看',
                icon: 'none'
            })
        } else {
            uni.showToast({
                title: '获取答案失败',
                icon: 'none'
            })
        }
        return null
    }
}

// 切换单个问题答案显示状态
const toggleAnswer = async (interview: any) => {
    // 检查登录状态
    if (!userStore.token) {
        // 跳转到登录页面
        uni.navigateTo({
            url: '/pages/login/login'
        })
        return
    }

    // 如果答案已经存在或者已经在显示中，直接切换显示状态
    if (interview.answer || answerVisibility.value[interview.id]) {
        answerVisibility.value[interview.id] = !answerVisibility.value[interview.id]
        return
    }

    // 如果还没有加载答案，则获取答案
    try {
        const answer = await getAnswer(interview.id)

        if (answer) {
            // 更新前端宝典对象，添加答案
            const index = interviews.value.findIndex(item => item.id === interview.id)
            if (index !== -1) {
                interviews.value[index] = {
                    ...interviews.value[index],
                    answer
                }
                // 显示答案
                answerVisibility.value[interview.id] = true
            }
        }
    } catch (err) {
        console.error('获取答案失败:', err)
        uni.showToast({
            title: '获取答案失败',
            icon: 'none'
        })
    }
}

// 切换所有答案显示状态
const toggleAllAnswers = () => {
    // 如果开启全部显示，可能需要逐个加载答案
    if (showAllAnswers.value) {
        interviews.value.forEach(interview => {
            answerVisibility.value[interview.id] = true
            // 如果没有答案，需要加载
            if (!interview.answer) {
                getAnswer(interview.id).then(answer => {
                    if (answer) {
                        const index = interviews.value.findIndex(item => item.id === interview.id)
                        if (index !== -1) {
                            interviews.value[index] = {
                                ...interviews.value[index],
                                answer
                            }
                        }
                    }
                })
            }
        })
    } else {
        // 关闭所有答案显示
        interviews.value.forEach(interview => {
            answerVisibility.value[interview.id] = false
        })
    }
}

function initData() {
    page.value = 1 // 重置页码
    interviews.value = [] // 清空当前列表
    answerVisibility.value = {} // 重置答案显示状态
    fetchInterviews() // 重新加载数据
}

// 监听筛选条件变化
watch([currentDifficulty, requirePremium], () => {
    initData()
})

// 获取难度对应的文字
const getDifficultyText = (difficulty: number) => {
    const info = difficultyMap[difficulty as keyof typeof difficultyMap]
    return info ? info.text : '未知'
}

// 获取难度对应的样式类
const getDifficultyClass = (difficulty: number) => {
    const difficultyClassMap: Record<number, string> = {
        1: 'difficulty-easy',
        2: 'difficulty-medium',
        3: 'difficulty-hard'
    }
    return difficultyClassMap[difficulty] || 'difficulty-default'
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
    const categoryMap: Record<number, string> = {
        1: '前端',
        2: '后端',
        3: '算法',
        4: '数据库',
        5: '网络',
        6: '系统设计',
        7: '项目管理',
        8: 'DevOps',
        9: '软技能'
    }
    return categoryMap[categoryId] || '未分类'
}

// 格式化日期
const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
            const minutes = Math.floor(diff / (1000 * 60))
            return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
        }
        return `${hours}小时前`
    } else if (days === 1) {
        return '昨天'
    } else if (days < 7) {
        return `${days}天前`
    } else {
        return date.toLocaleDateString('zh-CN')
    }
}

// 格式化答案内容（简单的markdown转HTML）
const formatAnswer = (answer: string) => {
    // 简单的markdown转换，实际项目中可以使用更完善的库
    return answer
        .replace(/\n\n/g, '<br><br>')
        .replace(/\n/g, '<br>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
}

// 点赞和收藏操作
const handleLike = async (interview: any) => {
    if (!userStore.token) {
        uni.showToast({
            title: '请先登录',
            icon: 'none'
        })
        return
    }
    try {
        await likeInterview(interview.id)
        interview.isLiked = !interview.isLiked
        interview.likeCount += interview.isLiked ? 1 : -1
    } catch (e) {
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        })
    }
}

const handleFavorite = async (interview: any) => {
    if (!userStore.token) {
        uni.showToast({
            title: '请先登录',
            icon: 'none'
        })
        return
    }
    try {
        await favoriteInterview(interview.id)
        interview.isFavorited = !interview.isFavorited
        interview.favoriteCount += interview.isFavorited ? 1 : -1
    } catch (e) {
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        })
    }
}

// 检查用户是否是会员
const checkUserIsPremium = () => {
    isPremium.value = userStore.userInfo?.isPremium || false
}

onMounted(() => {
    checkUserIsPremium()
    fetchInterviews()
})
</script>

<style lang="scss" scoped>
// 页面基底：更柔和的灰底，突出白卡片
.interview-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

// 顶部筛选卡片：圆角卡片 + 阴影 + 间距
.filter-bar {
  background: #fff;
  margin: 20rpx 20rpx 0;
  padding: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 6rpx 20rpx rgba(31, 41, 55, 0.08);
}

// 标签通用胶囊样式
@mixin pill($activeColor: #2b85e4) {
  padding: 12rpx 28rpx;
  margin-right: 12rpx;
  border-radius: 999rpx;
  font-size: 24rpx;
  white-space: nowrap;
  border: 1rpx solid #e5e7eb;
  background: #f2f4f7;
  color: #6b7280;
  transition: all 0.25s ease;
  &.active {
    background: #e8f3ff;
    color: $activeColor;
    border-color: $activeColor;
    font-weight: 600;
  }
}

.difficulty-tabs {
  display: flex;
  margin-bottom: 16rpx;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  &::-webkit-scrollbar { display: none; }
  .tab-item { @include pill(#2b85e4); }
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.premium-tabs {
  display: flex;
  .tab-item { @include pill(#2b85e4); }
}

.show-answers-control {
  display: flex;
  align-items: center;
  gap: 10rpx;
  .show-text { font-size: 24rpx; color: #6b7280; }
  .total-count { font-size: 24rpx; color: #9ca3af; }
}

// 列表区域
.content-scroll { flex: 1; height: 0; }
.content-wrapper { padding: 20rpx; }
.interview-list { min-height: 400rpx; }

.loading-container,
.error-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  .error-text { color: #ff3b30; }
  .empty-text { color: #9ca3af; }
}

.interview-cards { display: flex; flex-direction: column; gap: 20rpx; }

// 单条面试题卡片：更现代的卡片视觉，带细边 + 阴影
.interview-card {
  position: relative;
  overflow: hidden; // 用于裁剪右上角飘带
  padding: 28rpx;
  background: #fff;
  border-radius: 18rpx;
  border: 1rpx solid #eef0f4;
  box-shadow: 0 8rpx 22rpx rgba(31, 41, 55, 0.06);

  // VIP 右上角斜角飘带
  .vip-badge {
    position: absolute;
    top: -10rpx;
    right: -50rpx;
    width: 140rpx;
    text-align: center;
    transform: rotate(45deg);
    background: linear-gradient(90deg, #ffb23b, #ff8a00);
    padding: 16rpx 0 12rpx;
    box-shadow: 0 4rpx 8rpx rgba(255, 138, 0, 0.25);
    .vip-text {
      color: #fff;
      font-size: 20rpx;
      font-weight: 800;
      letter-spacing: 1rpx;
      display: block;
      transform: translateY(3rpx); // 微调文字位置以实现更好的视觉居中
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 18rpx;

    .question-title {
      flex: 1;
      margin-right: 20rpx;
      font-size: 30rpx;
      font-weight: 600;
      color: #1f2937;
      line-height: 1.5;
    }

    .difficulty-tag {
      padding: 6rpx 18rpx;
      border-radius: 999rpx;
      font-size: 22rpx;
      white-space: nowrap;
      &.difficulty-easy { background: #e7f9ef; color: #16a34a; border: 1rpx solid #b7f7ce; }
      &.difficulty-medium { background: #fff4e5; color: #c2410c; border: 1rpx solid #ffd5a3; }
      &.difficulty-hard { background: #ffeaea; color: #dc2626; border: 1rpx solid #ffc2c2; }
      &.difficulty-default { background: #eef2f7; color: #6b7280; border: 1rpx solid #e5e7eb; }
    }
  }

  .card-content {
    .content-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 18rpx;
      border-top: 1rpx solid #f0f2f5;

      .meta-info {
        display: flex;
        gap: 20rpx;
        font-size: 24rpx;
        color: #9ca3af;

        // 分类徽章：绿色风格
        .category {
          background: #e7f9ef;
          color: #16a34a;
          padding: 4rpx 14rpx;
          border-radius: 12rpx;
          border: 1rpx solid #b7f7ce;
          font-size: 20rpx;
        }
      }

      // 查看答案：改为文字按钮风格
      .toggle-answer-btn {
        padding: 0;
        background: transparent;
        border-radius: 0;
        .btn-text {
          color: #2563eb;
          font-size: 24rpx;
          text-decoration: underline;
        }
      }
    }

    .answer-content {
      margin-top: 18rpx;
      padding-top: 18rpx;
      border-top: 1rpx solid #f0f2f5;

      .answer-wrapper {
        background: #f8fafc;
        border-radius: 12rpx;
        padding: 22rpx;

        .answer-header {
          display: flex;
          align-items: center;
          margin-bottom: 14rpx;
          .answer-indicator { width: 6rpx; height: 24rpx; background: #2563eb; border-radius: 3rpx; margin-right: 12rpx; }
          .answer-label { color: #2563eb; font-weight: 700; }
        }
        .answer-text { line-height: 1.7; color: #334155; }
      }

      .answer-loading { text-align: center; padding: 40rpx; color: #9ca3af; }

      .action-buttons {
        display: flex;
        justify-content: center;
        gap: 60rpx;
        margin-top: 28rpx;
        .action-btn {
          display: flex;
          align-items: center;
          gap: 10rpx;
          padding: 14rpx 30rpx;
          border-radius: 999rpx;
          background: #f3f4f6;
          border: 1rpx solid #e5e7eb;
          color: #374151;
          transition: all 0.2s ease;
          &.liked { background: #e8f3ff; color: #2b85e4; border-color: #2b85e4; }
          &.favorited { background: #fff2e5; color: #ff8a00; border-color: #ffb23b; }
          .btn-icon { font-size: 30rpx; }
          .btn-count { font-size: 24rpx; font-weight: 600; }
        }
      }
    }
  }
}

.load-more,
.no-more {
  text-align: center;
  padding: 40rpx;
  color: #9ca3af;
  font-size: 24rpx;
}
</style>